import axios from "axios";
import { notification } from "antd";

const baseURL = "http://localhost:8000/";

const instance = axios.create({
  baseURL: baseURL,
  timeout: 1000,
  // headers: {'Authorization': 'cookie'} TODO: 这里要改为cookie
});
instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

// 请求拦截
instance.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const status = error.response?.status || 400;
    const message = error.response?.data?.message || "未知错误";
    notification.error({
      message: "Http Error",
      description: `${status}错误：${message}`,
      duration: 10,
    });
    return Promise.reject(error);
  }
);

type MethodType = "get" | "post" | "put" | "delete";

export function http(method: MethodType, url: string, params: object = {}) {
  const paramsTemp = method === "get" ? { params } : params;
  return new Promise((resolve, reject) => {
    instance[method](url, paramsTemp)
      .then(
        (response) => {
          resolve(response.data);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((error) => {
        reject(error);
      });
  });
}

export function getUrl(url: string) {
  return baseURL + url;
}

export default http;
